#include <avr/interrupt.h>
#include <avr/io.h>
#include "packet.h"

volatile unsigned char tx_done = 1;

ISR(USART_TX_vect)
{
	tx_done = 1;
	UCSRB &= ~(_BV(TXEN) | _BV(TXCIE));
}

volatile unsigned char haspacket;
volatile packet cmd;
volatile packet cmdtemp;

unsigned char pindex = 0;

unsigned char calcsum(void)
{
	unsigned char c = 0;
	for(unsigned char i = 0; i<sizeof(packet); i++)
		c += cmdtemp.packet[i];
	return c;
}

void handlebyte(char b)
{
	cmdtemp.packet[pindex++] = b;
	if(pindex >= sizeof(packet))
	{
		if(calcsum() != 255)
		{
			pindex--;
			for(unsigned char i = 0; i<(sizeof(packet)-1); i++)
				cmdtemp.packet[i] = cmdtemp.packet[i+1];
				
			return;
		}
		cmd = cmdtemp;
		haspacket = 1;
		pindex = 0;
	}
}

void transmitbyte(char b)
{
	tx_done = 0;
	UCSRB |= _BV(TXEN) | _BV(TXCIE);
	UDR = b;
}
